package com.lowcodeai.auth.controller;

import com.lowcodeai.auth.dto.LoginRequest;
import com.lowcodeai.auth.dto.LoginResponse;
import com.lowcodeai.auth.service.AuthService;
import com.lowcodeai.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 认证控制器
 * 
 * @author LowCodeAI
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Tag(name = "认证管理", description = "用户认证相关接口")
@Validated
public class AuthController {

    private final AuthService authService;

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录接口")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        return authService.login(request);
    }

    @PostMapping("/logout")
    @Operation(summary = "用户登出", description = "用户登出接口")
    public Result<Void> logout(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        return authService.logout(token);
    }

    @PostMapping("/refresh")
    @Operation(summary = "刷新Token", description = "刷新访问令牌")
    public Result<LoginResponse> refreshToken(@RequestParam String refreshToken) {
        return authService.refreshToken(refreshToken);
    }

    @GetMapping("/current-user")
    @Operation(summary = "获取当前用户", description = "获取当前登录用户信息")
    public Result<LoginResponse.UserInfo> getCurrentUser(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        return authService.getCurrentUser(token);
    }

    @PostMapping("/validate")
    @Operation(summary = "验证Token", description = "验证访问令牌是否有效")
    public Result<Boolean> validateToken(HttpServletRequest request) {
        String token = getTokenFromRequest(request);
        boolean isValid = authService.validateToken(token);
        return Result.success(isValid);
    }

    /**
     * 从请求中获取Token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
} 